package com.chushouya.order.service.api.impl;

import com.general.framework.core.lang.Strings;
import com.chushouya.manager.dao.entity.PartnerPromoteEntity;
import com.chushouya.manager.service.common.PartnerPromoteCommonService;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.dto.mq.promote.PromoteMqDTO;
import com.chushouya.order.service.api.PartnerPromoteApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 合作商推广API服务实现类
 * 
 * @author chushouya
 * @date 2025-08-17
 */
@Service
@Slf4j
public class PartnerPromoteApiServiceImpl implements PartnerPromoteApiService {

    @Resource
    private PartnerPromoteCommonService partnerPromoteCommonService;

    @Resource
    private OrderRepository orderRepository;

    @Override
    public Boolean processPartnerPromote(PromoteMqDTO promoteMqDTO) {
        try {
            Long orderId = promoteMqDTO.getOrderId();
            String promoteLabel = promoteMqDTO.getPromoteLabel();
            
            log.info("开始处理合作商推广，订单ID: {}, 推广标签: {}", orderId, promoteLabel);
            
            // 参数校验
            if (orderId == null || orderId <= 0) {
                log.error("订单ID无效: {}", orderId);
                return false;
            }
            
            if (Strings.isEmpty(promoteLabel)) {
                log.error("推广标签为空，订单ID: {}", orderId);
                return false;
            }

            OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
            if (Objects.isNull(orderEntity)) {
                log.error("订单不存在，订单ID: {}", orderId);
                return false;
            }

            PartnerPromoteEntity partnerPromoteEntity = partnerPromoteCommonService.selectByPromoteLabel(promoteLabel);
            if (Objects.isNull(partnerPromoteEntity)) {
                log.error("推广标签不存在，推广标签: {}", promoteLabel);
                return false;
            }
            // 更新订单的推广标签
            OrderEntity updateOrder = new OrderEntity();
            updateOrder.setOrderId(orderId);
            updateOrder.setChannel(promoteLabel);
            updateOrder.setPartnerId(partnerPromoteEntity.getPartnerId());
            updateOrder.setPartnerName(partnerPromoteEntity.getPartnerName());
            updateOrder.setPartnerType(partnerPromoteEntity.getPartnerType());
            orderRepository.updateByPrimaryKeySelective(updateOrder);

            
            log.info("合作商推广处理完成，订单ID: {}, 推广标签: {}", orderId, promoteLabel);
            return true;
            
        } catch (Exception e) {
            log.error("合作商推广处理异常，订单ID: {}, 错误信息: {}", 
                promoteMqDTO.getOrderId(), e.getMessage(), e);
            return false;
        }
    }
}
